﻿using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace fund
{
    public class Worker
    {
        /// <summary>
        ///
        /// </summary>
        private Fund fund;

        /// <summary>
        ///
        /// </summary>
        private ShowProgressDelegate showProgress;

        /// <summary>
        ///
        /// </summary>
        private int currentNum;

        /// <summary>
        ///
        /// </summary>
        private int numOfThread;

        private Random r = new Random();

        public Worker()
        { }

        public Worker(Fund code, int currentNum, int numOfThread, ShowProgressDelegate showProgress)
        {
            this.fund = code;
            this.showProgress = showProgress;
            this.currentNum = currentNum;
            this.numOfThread = numOfThread;
        }

        /// <summary>
        /// 获取净值
        /// </summary>
        /// <param name="FundType"></param>
        /// <param name="FundDate"></param>
        /// <param name="cts"></param>
        /// <returns></returns>
        public List<Fund> GetFund(int FundType, out string FundDate, CancellationTokenSource cts)
        {
            List<Fund> table1 = new List<Fund>();
            FundDate = "";
            long rt = Utility.GetTimeLikeJS(DateTime.Today);
            string url = "http://fund.eastmoney.com/Data/Fund_JJJZ_Data.aspx?t=1&lx=" + FundType + "&letter=&gsid=&text=&sort=zdf,desc&page=1,9999&dt=" + rt.ToString() + "&atfc=&onlySale=0";

            string html = HtmlParseUtitly.GetHtmlSource(url, Encoding.UTF8);
            if (!string.IsNullOrEmpty(html))
            {
                html = html.Substring(7).TrimEnd(';');
                var _jObject = JObject.Parse(html);
                table1 = JArrayConverter.ArrayToList_JZ(_jObject["datas"] as JArray);
                FundDate = _jObject["showday"][0].ToString();
                for (int i = 0; i < table1.Count; i++)
                {
                    switch (FundType)
                    {
                        case 2:
                            table1[i].FundType = "2股票型";
                            break;

                        case 3:
                            table1[i].FundType = "2股票型";//3(混合型)
                            break;

                        case 13:
                            table1[i].FundType = "4债券型";//13债券型
                            break;

                        case 5:
                            table1[i].FundType = "5指数型";
                            break;

                        default:
                            break;
                    }
                    switch (table1[i].IsCanBuy)
                    {
                        case "1":
                        case "3":
                        case "8":
                        case "9":
                        case "2":
                            table1[i].IsCanBuy = "可以购买";
                            break;

                        case "4":
                            table1[i].IsCanBuy = "暂停申购";
                            break;

                        case "5":
                            table1[i].IsCanBuy = "封闭期";
                            break;

                        case "6":
                            table1[i].IsCanBuy = "暂停申购";
                            break;

                        case "7":
                            table1[i].IsCanBuy = "基金终止";
                            break;

                        case "10":
                            table1[i].IsCanBuy = "发行失败";
                            break;

                        default:
                            table1[i].IsCanBuy = "未开通";
                            break;
                    }
                }
            }
            return table1;
        }

        /// <summary>
        /// 查询排名
        /// </summary>
        /// <param name="state"></param>
        public void workPM(object state)
        {
            try
            {
                string url = " http://fundsoft.eastmoney.com/fundapp2/symx.aspx?fc=" + (fund.FundCode) + "&random=" + r.Next();
                string html = HtmlParseUtitly.GetHtmlSource(url, Encoding.UTF8);
                if (string.IsNullOrEmpty(html)) return;

                HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
                document.LoadHtml(html);
                HtmlNode rootNode = document.DocumentNode;

                string s1 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[1]/td[4]");//今年以来
                if (s1 == "---") s1 = "---|---";
                string s2 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[2]/td[4]");//最近1周
                if (s2 == "---") s2 = "---|---";
                string s3 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[3]/td[4]");//最近1月
                if (s3 == "---") s3 = "---|---";
                string s4 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[4]/td[4]");//最近3月
                if (s4 == "---") s4 = "---|---";
                string s5 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[5]/td[4]");//  最近6月
                if (s5 == "---") s5 = "---|---";
                string s6 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[6]/td[4]");// 最近1年
                if (s6 == "---") s6 = "---|---";
                string s7 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[7]/td[4]");//  最近2年
                if (s7 == "---") s7 = "---|---";
                string s8 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[8]/td[4]");// 最近3年
                if (s8 == "---") s8 = "---|---";
                string s9 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[9]/td[4]");//  最近5年
                if (s9 == "---") s9 = "---|---";
                string s10 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[10]/td[4]");//  成立来

                fund.ColRank = ParseInt(s1.Split('|')[0]);
                fund.ColRank1 = ParseInt(s1.Split('|')[1]);

                fund.ColRank1W = ParseInt(s2.Split('|')[0]);
                fund.ColRank1W1 = ParseInt(s2.Split('|')[1]);

                fund.ColRank1M = ParseInt(s3.Split('|')[0]);
                fund.ColRank1M1 = ParseInt(s3.Split('|')[1]);

                fund.ColRank3M = ParseInt(s4.Split('|')[0]);
                fund.ColRank3M1 = ParseInt(s4.Split('|')[1]);

                fund.ColRank6M = ParseInt(s5.Split('|')[0]);
                fund.ColRank6M1 = ParseInt(s5.Split('|')[1]);

                fund.ColRank1Y = ParseInt(s6.Split('|')[0]);
                fund.ColRank1Y1 = ParseInt(s6.Split('|')[1]);

                fund.ColRank2Y = ParseInt(s7.Split('|')[0]);
                fund.ColRank2Y1 = ParseInt(s7.Split('|')[1]);

                fund.ColRank3Y = ParseInt(s8.Split('|')[0]);
                fund.ColRank3Y1 = ParseInt(s8.Split('|')[1]);

                fund.ColRank5Y = ParseInt(s9.Split('|')[0]);
                fund.ColRank5Y1 = ParseInt(s9.Split('|')[1]);

                Console.WriteLine(fund.FundCode + " worker thread back...");
            }
            catch
            {
                fund.ColRank = 9999;
            }

            // 显示进度条
            showProgress(numOfThread, currentNum + 1);
        }

        /// <summary>
        /// 查询历史净值
        /// </summary>
        /// <param name="state"></param>
        public void workHistoryJZ(object state)
        {
            try
            {
                string url = "http://fund.eastmoney.com/f10/F10DataApi.aspx?type=lsjz&code=" + (fund.FundCode) + "&page=1&per=5&edate=" + DateTime.Today.ToShortDateString() + "&rt=" + r.Next();
                string html = HtmlParseUtitly.GetHtmlSource(url, Encoding.GetEncoding("gb2312"));
                if (string.IsNullOrEmpty(html)) return;
                html = html.Replace("var apidata=", "").TrimEnd(';'); ;
                var _jObject = JObject.Parse(html);

                HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
                document.LoadHtml(_jObject["content"].ToString());
                HtmlNode rootNode = document.DocumentNode;

                fund.GrowthRate = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[1]/td[4]");
                fund.GrowthRate1 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[2]/td[4]");//
                if (fund.GrowthRate1 == "") fund.GrowthRate1 = "-";
                fund.GrowthRate2 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[3]/td[4]");//
                if (fund.GrowthRate2 == "") fund.GrowthRate2 = "-";
                fund.GrowthRate3 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[4]/td[4]");//
                if (fund.GrowthRate3 == "") fund.GrowthRate3 = "-";
                fund.GrowthRate4 = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr[5]/td[4]");//
                if (fund.GrowthRate4 == "") fund.GrowthRate4 = "-";

                Console.WriteLine(fund.FundCode + " worker thread back...");
            }
            catch
            {
                fund.ColRank = 9999;
            }

            // 显示进度条
            showProgress(numOfThread, currentNum + 1);
        }

        /// <summary>
        /// 查询基础信息
        /// </summary>
        /// <param name="state"></param>
        public void workJCXX(object state)
        {
            try
            {
                string url = "http://fundsoft.eastmoney.com/fundapp/jjzl.aspx?fc=" + (fund.FundCode) + "&random=" + r.Next();
                string html = HtmlParseUtitly.GetHtmlSource(url, Encoding.UTF8);
                if (string.IsNullOrEmpty(html)) return;

                HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
                document.LoadHtml(html);
                HtmlNode rootNode = document.DocumentNode;

                fund.ColBuildDate = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr/td[@class='PDate']");
                string scale = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr/td[@class='scope']").Replace("亿元", "");
                fund.ColScale = scale.Trim() == "" ? 0 : decimal.Parse(scale);//

                // fund.ColManager = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr/td[@class='fundMgr']");//
                fund.ColManager = string.Join("，", HtmlParseUtitly.GetNodesInnerText(rootNode, "//div[@class='summary']/p[count(span)!=1]")).Replace("姓名：", "").Replace("上任日期：", "~");//

                fund.ColCompany = HtmlParseUtitly.GetNodeInnerText(rootNode, "//tbody/tr/td[@class='fundMgmt']");//

                Console.WriteLine(fund.FundCode + " worker thread back...");
            }
            catch
            {
                fund.ColRank = 9999;
            }

            // 显示进度条
            showProgress(numOfThread, currentNum + 1);
        }

        /// <summary>
        /// 最新估值
        /// </summary>
        /// <param name="state"></param>
        public List<Fund> workGZ()
        {
            List<Fund> gz = new List<Fund>();
            Fund fund;
            try
            {
                //估值
                //string url = "http://fund.eastmoney.com/f10/F10DataApi.aspx?type=gz&code=" + (fund.FundCode) + "&rt=" + r.Next();
                string url = " http://fund.eastmoney.com/fundguzhi.html";
                string html = HtmlParseUtitly.GetHtmlSource(url, Encoding.GetEncoding("gb2312"));
                if (string.IsNullOrEmpty(html)) return gz;

                HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
                document.LoadHtml(html);
                HtmlNode rootNode = document.DocumentNode;
                HtmlNodeCollection ArticleUrlList = rootNode.SelectNodes("//table[@id='oTable']/tbody/tr");

                foreach (HtmlNode articleUrlNode in ArticleUrlList)
                {
                    fund = new Fund();
                    fund.FundCode = HtmlParseUtitly.GetNodeInnerText(articleUrlNode, "td[3]");
                    fund.FundName = HtmlParseUtitly.GetNodeInnerText(articleUrlNode, "td[4]/a[1]");
                    fund.FundNo = int.Parse(HtmlParseUtitly.GetNodeInnerText(articleUrlNode, "td[2]"));
                    string ljjz = HtmlParseUtitly.GetNodeInnerText(articleUrlNode, "td[10]");
                    fund.ljjz = ljjz == "---" ? -1 : decimal.Parse(ljjz);
                    fund.gz = HtmlParseUtitly.GetNodeInnerText(articleUrlNode, "td[6]");
                    gz.Add(fund);
                }
            }
            catch
            {
                return gz;
            }
            return gz;
        }

        /// <summary>
        /// 百分比排名
        /// </summary>
        /// <returns></returns>
        public List<Fund> workPM()
        {
            List<Fund> table1 = new List<Fund>();

            try
            {
                //估值
                //string url = "http://fund.eastmoney.com/f10/F10DataApi.aspx?type=gz&code=" + (fund.FundCode) + "&rt=" + r.Next();
                string url = "http://fund.eastmoney.com/data/rankhandler.aspx?op=ph&dt=kf&ft=all&rs=&gs=0&sc=zzf&st=desc&sd=2015-06-01&ed=" + DateTime.Today.ToShortDateString() + "&qdii=&tabSubtype=,,,,,&pi=1&pn=10000&dx=0&v=" + r.Next();
                string html = HtmlParseUtitly.GetHtmlSource(url, Encoding.UTF8);
                if (string.IsNullOrEmpty(html)) return table1;

                html = html.Substring(15).TrimEnd(';');
                var _jObject = JObject.Parse(html);
                table1 = JArrayConverter.ArrayToList_PM(_jObject["datas"] as JArray);
            }
            catch
            {
                return table1;
            }
            return table1;
        }

        private int ParseInt(string intValue)
        {
            int aa = -1;
            if (!int.TryParse(intValue, out aa))
                aa = -1;
            return aa;
        }
    }
}